package br.ufpe.cin.rdfilter.query;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import br.ufpe.cin.rdfilter.feedback.Triple;

import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.RDFNode;

public class QueryManager {

	private List<String> columnsName = new ArrayList<String>();
	private List<String> dataQuery = new ArrayList<String>();
	private File dir;
	private List<String> queries = new ArrayList<String>();
//	
//	public QueryManager(File dir){
//		this.dir=dir;
//	}
	
	public void executeQuery(String endpoint, String query, String idQuery) {
		QueryExecution queryExecution = QueryExecutionFactory.sparqlService(
				endpoint, query);
		ResultSet results = queryExecution.execSelect();
		// get column names
		columnsName = results.getResultVars();

		// get lines
		while (results.hasNext()) {

			QuerySolution result = results.next();

			Iterator<String> varNames = result.varNames();

			RDFNode answerField;

			while (varNames.hasNext()) {
				answerField = result.get(varNames.next());
				dataQuery.add(answerField + "");
			}

		}
	}

	public List<String> loadQuery() {

		try {
			FileReader reader = new FileReader(dir);
			BufferedReader in = new BufferedReader(reader);
			String line = null;

			while ((line = in.readLine()) != null) {
				queries.add(line);
			}
			for (int i = 0; i < queries.size(); i++)
				System.out.println(queries.get(i));

			in.close();
			reader.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return queries;
	}

	public List<String> getColumn() {
		return columnsName;
	}

	public List<String> getDataQuery() {
		return dataQuery;
	}

	public File getDir() {
		return dir;
	}

	public void setDir(File dir) {
		this.dir = dir;
	}

	
}
